package com.beiding.jsonanalyzer.analyze.func.openfunc;

import com.beiding.jsonanalyzer.analyze.func.FuncFactory;
import com.beiding.jsonanalyzer.analyze.func.base.EasyAggFunc;
import com.beiding.jsonanalyzer.analyze.func.base.FuncFactoryAdaptor;

import java.util.List;

/**
 * 平均值
 *
 * @author 丁常磊
 * @date 2022/5/10 15:53
 */

public class Avg  {

    public static FuncFactory of(Object exp, boolean distinct) {
        return FuncUtils.buildForEasyAgg(new FuncFactoryAdaptor<EasyAggFunc>(){
            @Override
            protected EasyAggFunc newInstance() {
                return new EasyAggFunc() {
                    @Override
                    public Object agg(List<Object> list) {
                        int count = 0;
                        double sum = 0;

                        for (Object o : list) {
                            if (o instanceof Number) {
                                count++;
                                sum += ((Number) o).doubleValue();
                            }
                        }
                        if (count == 0) {
                            return null;
                        }
                        return sum / count;
                    }

                };
            }
        }, exp, distinct);
    }

    public static FuncFactory of(Object exp) {
        return of(exp, false);
    }

}
